package com.yutian.springbootvue.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * MDC日志跟踪号
 */
public class TraceUserFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(TraceUserFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String name = httpRequest.getParameter("name");
        if(null != name && name.trim().length() > 0){
            httpRequest.setAttribute("name", name + System.currentTimeMillis());
        }

        log.debug("uri: {}", httpRequest.getRequestURI());

        chain.doFilter(httpRequest, httpResponse);


    }

    @Override
    public void destroy() {

    }

}
